# Authors: Damian 'Rush' Kaczmarek (main), Adam 'dredzik' Kuczynski (login)
# License: MIT

package Shoutbox;
use base Module;
use strict;
use utf8;
use XML::RSS;
use LWP::Simple;
use LWP::UserAgent;
use HTTP::Request::Common;
use Compress::Zlib;
use HTML::Entities;
use Digest::CRC qw(crc16);
use Encode;
use POSIX qw(strftime);

my $refresh  = Config::get('refresh',  '30');
my $username = Config::get('username', 'my_secret_username');
my $password = Config::get('password', 'my_secret_password');
my $lastguid;
my $lastid;
my $sid;

sub color_nick
{
	my $colorid = 2 + (int(crc16($_[0])) % 9);

	if (length($colorid) < 2) {    # Irc colors should be 2 bytes, so for example instead of 1, it should be 01
		$colorid = "0" . int($colorid);
	}
	return chr(3) . $colorid . $_[0] . chr(15);

}

sub BBCode
{                                      # try to interpret BBCode tags a little bit. to do: nested tags

	#	my $white = chr(3) . "00,01";

	my $bold      = chr(2);        # ...or italic
	my $underline = chr(31);
	my $end       = chr(15);

	$_[0] =~ s/(\[b\]|\[i\])/$bold/g;
	$_[0] =~ s/\[u\]/$underline/g;
	$_[0] =~ s/(\[\/b\]|\[\/i\]|\[\/u\])/$end/g;
	return $_[0];
}

sub notify
{
	my $item = $_[0];
	my $text = $item->{title};

	my $idx = index($text, ':');
	my $nick = substr($text, 0, $idx);
	$text = substr($text, $idx + 2);

	if ($text =~ /(http:\/\/\S+)( {2}(\S+))?( {2}(\S+))?( {2}(\S+))?( {2}(\S+))?/)
	{    # merge all parts of broken link
		if (length($1) > 55) {    # will have to fix it OR SLAP ARCZI
			my $url = $1 . $3 . $5 . $7 . $9;
			$text =~ s/(http:\/\/\S+)( {2}(\S+))?( {2}(\S+))?( {2}(\S+))?( {2}(\S+))?/$url/;
		}
	}
	decode_entities($text);
	$text = BBCode($text);
	if (length($text) > 423) {        # Cut the text if too long, put "..." at the end.
		$text = substr($text, 0, 420);
		$text .= "...";
	}

	Job::sync {
	    Core::send_msg(chr(15) . "[" . encode('utf8', color_nick($nick)) . "] " . encode('utf8', $text));
	};

	GetTitle::get_title($text);   # check if someone posted YouTube or Google Video link in shoutbox and do your job
	TinyURL::shorten($text);
}

sub check_shoutbox
{
	my $from_id = "";

	if (defined $lastid) {
		$from_id = "&sb_od=" . $lastid;
	}
	my $content = get("http://eti.dragoart.info/shoutbox_view.php?format=rss&sid=" . $sid . $from_id);

	if (defined $content) {    # Whether we actually got anything
		my $rss = XML::RSS->new;
		eval {$rss->parse($content);};
		if (defined $lastid) {
			foreach my $item (@{$rss->{'items'}}) {    # Iterate through each messages from the last run
				notify($item);
			}
		}
		if (@{$rss->{'items'}}) {                          # Update id, or first run
			my $lastitem = @{$rss->{'items'}}[@{$rss->{'items'}} - 1];
			my $guid     = $lastitem->{guid};
			$guid =~ m/id=(\d+)/;
			$lastid = $1;
		}
	}
}

sub login_loop
{
        $SIG{'STOP'} = sub {
	    print "Recieved signal STOP\n";
    	};
	
	while(1) {
	    my $ua       = LWP::UserAgent->new;
	    my $response = $ua->request(
		    POST 'http://eti.dragoart.info/login.php',
		    Content_Type => 'form-data',
		    Content => ["username" => $username, "password" => $password, "redirect" => "", "login" => "Zaloguj"]
	    );

	    $_ = $response->content;
	    if (/sid=([^"'&]+)/) {
		    $sid = $1;
		    check_shoutbox();
	    }
	    print "LOG\n";
	    sleep(5);
	}
}

Job::start(sub { }, sub { login_loop();});
